<template>
  <div style="display: flex;justify-content: center;align-items: center">
    <el-select
      v-model="copyValue"
      :filterable="filterable"
      :clearable="clearable"
      remote
      :remote-method="query01"
      :multiple="multiple"
      :placeholder="placeholder"
      :autocomplete="autoComplete || autocomplete"
      :size="size"
      :disabled="disabled"
      :collapse-tags="collapseTags"
      :allow-create="allowCreate"
      style="width:100%;"
      :style="selectStyle"
      :popper-append-to-body="popperAppendToBody"
      @change="updateValue"
      @focus="focusHandler"
      @visible-change="queryUrl"
    >
      <div v-if="jsonAdd" >
        <div style="padding: 10px">
          <el-input
            v-model="keyword"
            :placeholder="url?'请输入内容搜索':'输入内容回车可创建'"
            style="margin: auto"
            class="input-with-select"
            @keyup.enter.native="addNewItem"
          />
        </div>
      </div>
      <el-option-group label="可选值1">
        <div v-if="url === 'api/dropDown/basCustomerList'" class="flex flex-row  select_title" style="padding-left: 20px;padding-right: 20px">
          <div class="fl1">编号</div><div class="fl2">名称</div><div class="fl3">地址</div>
        </div>
        <el-option
          v-for="(item,index) in dataList"
          :key="item[valueKey] || index"
          :label="item[labelKey]"
          :value="item[valueKey]"
        >
          <div v-if="url === 'api/dropDown/basCustomerList'" :class="{'rowOne':(index % 2)}" class="flex flex-row select_customer_li">
            <div class="fl1">{{ item.code }}</div><div class="fl2">{{ item.name }}</div><div class="fl3">{{ item.address }}</div>
          </div>
        </el-option>
      </el-option-group>
      <div v-if="url" style="float: right;margin-right:10px;padding-bottom: 10px">
        <el-pagination
          :current-page="pageInfo.page"
          :page-size="pageInfo.size"
          layout="total, prev, pager, next"
          :total="pageInfo.total"
          :pager-count="5"
          @current-change="handleCurrentChange"
        />
      </div>

    </el-select>
  </div>

</template>

<script>
import request from '@/utils/request'

export default {
  name: 'ZSelect',
  props: {
    // 绑定值
    value: [String, Number, Object, Array],
    disabled: {
      type: Boolean,
      default: false
    },
    label: {
      default: '', // 已经选中的值内容
      type: String
    },
    url: String, // 如果不传url,则使用自定义模式
    json: String, // 没有url时，这个json不能为空，且要有isSelect字段
    // option的label在列表中对应的key
    labelKey: {
      type: String,
      default: 'name'
    },
    // option的value在列表中对应的key
    valueKey: {
      type: String,
      default: 'id'
    },
    isLast: {
      type: Boolean,
      default: false
    },
    // 参数
    params: {
      type: Object,
      default: function() {
        return {}
      }
    },
    // 其他参数
    autocomplete: {
      type: String,
      default: 'off'
    },
    /** @Deprecated in next major version */
    autoComplete: {
      type: String,
      validator(val) {
        process.env.NODE_ENV !== 'production' &&
        console.warn('[Element Warn][Select]\'auto-complete\' property will be deprecated in next major version. please use \'autocomplete\' instead.')
        return true
      }
    },
    automaticDropdown: Boolean,
    size: String,
    clearable: {
      type: Boolean,
      default: true
    },
    filterable: {
      type: Boolean,
      default: true
    },
    allowCreate: Boolean,
    loading: Boolean,
    popperClass: String,
    remote: Boolean,
    loadingText: String,
    noMatchText: String,
    noDataText: String,
    remoteMethod: Function,
    filterMethod: Function,
    multiple: Boolean,
    multipleLimit: {
      type: Number,
      default: 0
    },
    placeholder: {
      type: String,
      required: false,
      default: '请下拉选择'
    },
    defaultFirstOption: Boolean,
    reserveKeyword: Boolean,
    collapseTags: {
      type: Boolean,
      default: false
    },
    popperAppendToBody: {
      type: Boolean,
      default: true
    },
    // 数据实际层级
    dataKey: {
      type: String,
      default: ''
    },
    // 翻页参数实际层级
    dataTotalKey: {
      type: String,
      default: ''
    },
    // 翻页参数实际层级
    showName: {
      type: String,
      default: ''
    },
    jsonAdd: {
      type: Boolean,
      default: false
    },
    selectStyle:{
      type:   Object,
      default: ()=>{}
    },
  },
  data() {
    return {
      copyValue: this.value ? typeof (this.value) === 'string' ? this.value.split(',') : this.value : this.value,
      keyword: '',
      // 下拉列表
      jsonDataList: [],
      dataList: [],
      oldLabel: '',
      pageInfo: {
        page: 1,
        size: 20,
        total: 0
      }
    }
  },

  watch: {
    value: {
      handler: function(val) {
        // const copyValue = this.multiple ? typeof (val) === 'string' ? val.split(',') : typeof (val) === 'string' : val
        if (this.multiple) {
          if (this.copyValue === this.value || this.value === this.copyValue.join(',')) {
            return false
          }

          if (typeof val === 'string') { this.copyValue = val.split(',') } else if (typeof val === undefined || val === null) {
            this.$emit('update:value', '')
            this.copyValue = []
          } else if (val.length === 0) {
            this.copyValue = []
          }
        } else {
          this.copyValue = this.value
        }
        this.oldLabel = this.label
        this.addSelect()
      },
      deep: true
    },

    // showName(n,o){
    //   this.dataList = []
    //   const data={}
    //   if (!this.labelKey){
    //     return
    //   }
    //   data[this.labelKey] = this.showName
    //   data[this.valueKey] = this.value
    //   this.dataList.push(data)
    // },

    // params: {
    //   handler: function(val) {
    //     // 如果有一个是undefined,则不查询
    //     for (const key in val) {
    //       if (!val[key]) {
    //         return false
    //       }
    //     }
    //     this.getList()
    //   },
    //   deep: true
    // },
    // keyword: function(n) {
    //   // this.pageInfo.page = 1
    //   this.getList(n)
    // },
    // url: function(n) {
    //   // this.pageInfo.page = 1
    //   this.getList(n)
    // },
    json: function(n) {
      this.detailJson()
    }

  },
  mounted() {
    this.addSelect()
  },
  // mounted() {
  //   if (this.url) {
  //     this.getOne()
  //     this.getList()
  //   } else {
  //     this.detailJson()
  //   }
  // },
  methods: {
    addSelect() {
      setTimeout(() => {
        if (this.value) {
          try {
            if (this.multiple) {
              const labelKey = this.showName.split(',')
              if (labelKey.length !== this.copyValue.length) {
                return
              }
              for (let i = 0; i < this.copyValue.length; i++) {
                const data = {}
                data[this.labelKey] = labelKey[i]
                data[this.valueKey] = this.copyValue[i]
                if (!this.dataList.find(item => item[this.valueKey] === this.copyValue[i])) {
                  this.dataList.push(data)
                }
              }
            } else {
              if (this.showName) {
                const data = {}
                data[this.labelKey] = this.showName
                data[this.valueKey] = this.copyValue
                this.$set(this.dataList, 0, data)
              }
            }
            this.$forceUpdate()
          } catch (e) {
            console.error(e)
          }
        }
      },
      100)
    },
    query01(query) {
      this.keyword = query
      this.getList(query)
    },
    enter(e){
    },
    detailJson() {
      if (this.json) {
        this.dataList = JSON.parse(this.json)
        this.jsonDataList = this.dataList
      }
      const obj = this.dataList.find(data => {
        return data.isSelected
      })
      if (obj) {
        this.copyValue = obj[this.valueKey]
      }
    },
    addNewItem() {
      const obj = {
        [this.valueKey]: this.keyword,
        [this.labelKey]: this.keyword,
        isSelected: true
      }
      for(let i of this.dataList){
        i.isSelected=false
      }
      const emptyIndex = this.dataList.findIndex(item=>item[this.valueKey] === ' ')
      ~emptyIndex
      &&
      this.dataList.splice(emptyIndex,1)
      if (!this.url) {
        // 没有传url，就用自定义方式
        this.dataList.push(obj)
      }
      this.$emit('update:json',JSON.stringify(this.dataList))
      this.$forceUpdate()
    },
    getOne() {
      if (!this.copyValue) {
        return false
      }
      const params = {}
    },

    getList(n) {
      // eslint-disable-next-line eqeqeq
      if (this.url == null || this.url == '') {
        const list = this.jsonDataList.filter(item => item[this.labelKey].includes(this.keyword))
        this.dataList = list
        return false
      } else if (this.url === 'api/basBank/getBasBanksById') {
        this.url = 'api/dropDown/basBankList'
        this.valueKey = 'id'
        this.labelKey = 'name'
      }
      const oldList = []
      if (this.multiple) {
        this.dataList.forEach(item => {
          if (this.copyValue.includes(item[this.valueKey])) {
            oldList.push(item)
          }
        })
      }
      // 使用url查询
      const params = Object.assign({
        page: this.pageInfo.page,
        size: this.pageInfo.size
      }, this.params)
      if (this.keyword) {
        params['keyword'] = this.keyword
      }
      if (n == '') {
        params['keyword'] = this.keyword
      }
      if (this.isLast) {
        params['isLast'] = 1
      }
      const para = Object.assign({}, this.params)
      request({
        url: this.url,
        method: 'get',
        params
      }).then(res => {
        let _data = res.data
        // eslint-disable-next-line no-eval
        if (this.dataKey) _data = eval('(res' + this.getKeyString(this.dataKey) + ')')
        else {
          // 兼容之前接口
          if (res.content) {
            _data = res.content
          } else if (res.data) {
            _data = res.data.content || res.data
          }
        }
        if (this.url === 'api/basBank/getBasBanksById') {
          _data.bankId = _data.id
          _data.bankName = _data.name
        }

        if (this.copyValue instanceof Array) _data = _data.filter(item => !this.copyValue.includes(item[this.valueKey].toString()))

        try {
          this.pageInfo.total = res.totalElements || res.data.totalElements || 0
        } catch (e) {
          this.pageInfo.total = 0
        }
        this.dataList = oldList.concat(_data || [])

        // 去重
        this.dataList = this.uniqObjInArray(this.dataList)
        this.$forceUpdate()
        // eslint-disable-next-line no-eval
        if (this.dataTotalKey) this.pageInfo.total = eval('(res' + this.getKeyString(this.dataTotalKey) + ')')
      })
    },
    // 获取对应的key的字符串拼接
    getKeyString(string = '') {
      if (!string) return []
      else return string.split('.').reduce((a, b) => a + `['${b}']`, '')
    },
    // 更新值
    updateValue(_data) {
      //

      this.keyword = null
      if (!this.url && !this.json) {
        this.dataList.forEach(data => {
          data.isSelected = false
        })
        const obj = this.dataList.find(data => {
          return _data == data[this.valueKey]
        })
        obj['isSelected'] = true

        this.$emit('update:json', JSON.stringify(this.dataList))
        return false
      }
      if ((typeof this.value === 'string' || this.value === undefined || this.value === null) && this.multiple) {
        const value = this.copyValue.join(',')
        this.$emit('update:value', value)
      } else {
        this.$emit('update:value', this.copyValue)
      }

      // 直接将数据传过去

      const objList = this.dataList.find(o => o[this.valueKey] == this.copyValue)
      // eslint-disable-next-line eqeqeq
      this.$emit('getChange', objList)
      // eslint-disable-next-line eqeqeq
      this.$emit('change', objList)
    },
    // 翻页
    handleCurrentChange(val) {
      this.pageInfo.page = val
      this.getList()
    },
    focusHandler() {
      this.$emit('focus')
    },
    // 下拉才请求接口
    queryUrl(val) {
      if (val) {
        // setTimeout(()=>{this.$refs.ipt.$el.querySelector('input').focus()},500)
        if (this.url) {
          this.getOne()
          this.getList()
        } else {
          this.detailJson()
        }
      }
    },
    uniqObjInArray(objarray) {
      const len = objarray.length // 数组长度
      const tempJson = {}// 缓存对象
      const res = []// 中间数组

      for (let i = 0; i < len; i++) {
        // 利用缓存对象的属性去重
        if (!tempJson[JSON.stringify(objarray[i])]) {
          res.push(objarray[i])
          tempJson[JSON.stringify(objarray[i])] = true
        }
      }
      return res
    }

  }

}

</script>

<style  lang="scss" scoped>
.flex{
  display: flex;
}
.flex-row{
  flex-direction: row;
}
.fl1{
  flex:1;
  overflow: hidden;
}
.select_title{
  height: 40px;
  div{
    border: rgb(200,200,200) solid 1px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
.select_customer_li{
  border: rgb(200,200,200) 1px solid;
  div{
    border: rgb(200,200,200) solid 1px;
  }
}
.rowOne{
  background-color: rgba(192,250,233,0.3);
}
.fl2{
  flex:2;
  overflow: hidden;
}
.fl3{
  flex:1;
  overflow: hidden;
}
.add{
  padding : 30px;
}
</style>

